package com.wcfsy.wechat.wx.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wcfsy.wechat.wx.util.Constant;
import com.wcfsy.wechat.wx.util.WechatUtil;

@Controller
@RequestMapping("/weixin/")
public class WechatController {

	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private WechatUtil wechatUtil;
	
	/** 
     * 校验信息是否是从微信服务器发过来的。 
     *  
     * @param weChat 
     * @param out 
     */  
    @RequestMapping(value="signature", produces = "application/json;charset=UTF-8")  
    @ResponseBody
    public void valid(HttpServletResponse response,HttpServletRequest request) {  
    	try {
    		response.setCharacterEncoding("utf-8");
    		logger.info("============start==============" + request.getMethod());
	    	if("GET".equals(request.getMethod())){
	    		logger.info("===== 签名  ====");
	    		signature(request,response);
	    	}else{
	    		logger.info("===== 业务  ====");
				wechatUtil.acceptMessage(request, response);
	    	}
    	} catch (IOException e) {
    		logger.error("签名错误" , e);
		}
    } 
	
	public void signature(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		logger.info("signature=" + signature +",timestamp="+timestamp + ",nonce = " + nonce
				+",echostr = " + echostr);
		String[] values = {Constant.TOKEN, timestamp, nonce };
		Arrays.sort(values); // 字典序排序
		String value = values[0] + values[1] + values[2];
		String sign = DigestUtils.shaHex(value);
		PrintWriter writer = response.getWriter();
		logger.info("sign =" + sign );
		logger.info("msg_signature =" + signature );
		logger.info("msg_signature vs sign ======================" + signature.equals(sign));
		if (signature.equals(sign)) {// 验证成功返回ehcostr
			writer.print(echostr);
		} else {
			writer.print("error");
		}
		writer.flush();
		writer.close();
	}
}
